package tool

import (
	"github.com/xormplus/xorm"
	_ "github.com/go-sql-driver/mysql"
	"shoping.zozoo.net/model"
)

type Orm struct {
	*xorm.Engine
}

var DbEngine *xorm.Engine

func OrmEngine(cfg *Config) (*Orm, error) {

	var (
		err  error
		conn string
	)

	conn = cfg.Database.User + ":" + cfg.Database.Password + "@/" + cfg.Database.DbName + "?charset=" + cfg.Database.Charset
	if DbEngine, err = xorm.NewEngine(cfg.Database.Driver, conn); err != nil {
		panic(err)
		return nil, err
	}

	DbEngine.ShowSQL(cfg.Database.ShowSql)

	//同步数据库结构
	err = DbEngine.Sync2(
		new(model.Product),
		new(model.Order),
		new(model.User),
	)

	if err != nil {
		panic(err)
		return nil, err
	}

	orm := &Orm{
		DbEngine,
	}

	return orm, nil
}
